import fetch from 'node-fetch';
import { createLogger } from '../modules/Logger.js'; // 修改引入方式

const API_BASE = 'http://hh2233.cn:10001/?types=token&qqid=';

class DanmakuKeyPlugin extends plugin {
  constructor() {
    super({
      name: 'danmaku_key_generator',
      dsc: '弹幕姬秘钥生成器',
      event: 'message',
      priority: 6,
      rule: [
        {
          reg: "^#获取辉辉的秘钥$",
          fnc: 'generateKey',
          permission: 'all'
        }
      ]
    });
    
    // 初始化日志实例
    this.logger = createLogger(this.name);
  }

  async generateKey(e) {
    const qqid = e.user_id;
    const apiUrl = `${API_BASE}${qqid}`;

    try {
      await e.reply('正在生成专属秘钥，请稍候...', true);
      const response = await this.fetchWithTimeout(apiUrl);
      
      if (!response.ok) {
        throw new Error(`API请求失败，状态码：${response.status}`);
      }

      const data = await response.json();

      if (!data || !data.token) {
        throw new Error('无效的API响应格式');
      }

      const resultMsg = [
        '════ 您的专属秘钥 ════',
        `动态秘钥：${data.token}`,
        '═══════════════════',
        '⚠️ 有效期：当天',
      ].join('\n');

      await e.reply(resultMsg, true);
      this.logger.info(`用户 ${qqid} 获取秘钥成功`); // 修改为 info

    } catch (error) {
      this.logger.error(`秘钥生成失败: ${error.message}`); // 修改为 error
      await e.reply([
        '秘钥生成失败，可能原因：',
        '1. 服务器连接超时',
        '2. 系统繁忙请稍后重试',
        '3. 请联系管理员检查服务状态'
      ].join('\n'));
    }
  }

  fetchWithTimeout(url, timeout = 8000) {
    return Promise.race([
      fetch(url),
      new Promise((_, reject) =>
        setTimeout(() => reject(new Error('请求超时')), timeout)
      )
    ]);
  }
}

export default DanmakuKeyPlugin;
